﻿#ifndef _CONNECTOR_H_
#define _CONNECTOR_H_
#pragma once

#include <memory>
#include <ctime>
#include "as_socket.h"
#include "base_type.h"

namespace as
{
	namespace net
	{
		class Address;
		class EpollWatch;
		class Channel;
		class Connector : public std::enable_shared_from_this<Connector>
		{
		public:
			typedef std::function<void(socket_fd)> NewConnectCb;
			Connector(std::shared_ptr<EpollWatch> &ep, Address &addr);

		public:
			void start();
			void stop();
			int connect();
			void reconnect();
			void retry(std::shared_ptr<Socket> &socket);
			void shutdown();
		public:
			void SetNewConnCb(NewConnectCb cb);

			void SetReConnectTime(std::time_t time);

		public:
			void connection(std::shared_ptr<Socket> &socket);

		public:
			void HandleWrite();
			void HandleError();

		private:
			Address server_addr_;
			bool connect_ = false; //是否启动
			uint8 state_;
			Socket socket_;
			std::weak_ptr<EpollWatch> ep_watch_;
			std::shared_ptr<Channel> channel_;
			NewConnectCb new_conn_cb_;
			std::time_t reconnect_time_ = 1000;//默认重连事件300毫秒
		};

		DEFINE_PTR(Connector);
	}
}

#endif